package com.approval.approvalapp.center.tz;

import android.app.ProgressDialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.approval.approvalapp.R;
import com.approval.approvalapp.bean.JsdxListBean;
import com.approval.approvalapp.bean.SelectJsonBean;
import com.approval.approvalapp.bean.UpSuccessBean;
import com.approval.approvalapp.index.cygn.qjshenqing.QjShenqingActivity;
import com.approval.approvalapp.util.ErrorBeanUtil;
import com.approval.approvalapp.util.SpUtil;
import com.approval.approvalapp.util.base.BaseActivity;
import com.approval.approvalapp.util.net.NetRequsetUtil;
import com.approval.approvalapp.util.net.interfacepac.NetDownResponse;
import com.approval.approvalapp.util.net.interfacepac.NetUpLoadResponse;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.suke.widget.SwitchButton;

import java.io.File;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class FbtzActivity extends BaseActivity {


    @Bind(R.id.back_iv)
    ImageView backIv;
    @Bind(R.id.titleTv1)
    TextView titleTv1;
    @Bind(R.id.tzjl_ll)
    LinearLayout tzjlLl;
    @Bind(R.id.iv1)
    ImageView iv1;
    @Bind(R.id.ybtztv1)
    TextView ybtztv1;
    @Bind(R.id.iv2)
    ImageView iv2;
    @Bind(R.id.hytztv2)
    TextView hytztv2;
    @Bind(R.id.bt_et)
    EditText btEt;
    @Bind(R.id.qxz_tv)
    TextView qxzTv;
    @Bind(R.id.jsdx_ll)
    LinearLayout jsdxLl;
    @Bind(R.id.switch_button)
    SwitchButton switchButton;
    @Bind(R.id.file_name)
    TextView fileName;
    @Bind(R.id.add_ll)
    LinearLayout addLl;
    @Bind(R.id.del_ll)
    LinearLayout delLl;
    @Bind(R.id.agree_tv)
    LinearLayout agreeTv;
    @Bind(R.id.sftv)
    TextView sftv;
    @Bind(R.id.fkqx_ll)
    LinearLayout fkqx_ll;
    @Bind(R.id.fkqx)
    TextView fkqx;
    @Bind(R.id.nr_et)
    EditText nr_et;
    private boolean sffk;
    private boolean isybtz = true;
    private String filepath;
    private String fkqxstr;
    List<JsdxListBean> jsdxListBeans = new ArrayList<>();
    List<JsdxListBean> jsdxListBeans2 = new ArrayList<>();
    private List<SelectJsonBean> ybtzlsit;
    private List<SelectJsonBean> ybtzlsit2;
    private String ybtzlsitstr;
    private ProgressDialog progressDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_fbtz;
    }

    @Override
    public void initView() {
        switchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                if (isChecked) {
                    sffk = true;
                    sftv.setText("是");
                    fkqx_ll.setVisibility(View.VISIBLE);
                } else {
                    sffk = false;
                    sftv.setText("否");
                    fkqx_ll.setVisibility(View.GONE);
                }
            }
        });

    }

    @Override
    public void initData() {

    }


    @OnClick({R.id.back_iv, R.id.iv1, R.id.iv2, R.id.jsdx_ll, R.id.add_ll, R.id.del_ll, R.id.agree_tv, R.id.fkqx_ll,R.id.tzjl_ll})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tzjl_ll:
                Intent c = new Intent();
                c.setClass(this,TzListActivity.class);
                startActivity(c);
                break;
            case R.id.fkqx_ll:
                TimePickerView pvTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {

                        long kstime = date.getTime() / 1000;
                        fkqxstr = kstime + "";
                        SimpleDateFormat format = new SimpleDateFormat("yyyy MM-dd HH:mm:ss");
                        fkqx.setText(format.format(date));

                    }
                }).setType(new boolean[]{true, true, true, true, true, true})
                        .setTitleText("选择开始时间").build();
                pvTime.show();
                break;
            case R.id.back_iv:
                finish();
                break;
            case R.id.iv1:
                if (isybtz) {
                    //已经是一般通知
                    return;
                } else {
                    iv1.setBackgroundResource(R.drawable.case_on);
                    iv2.setBackgroundResource(R.drawable.case_off);
                    ybtztv1.setTextColor(Color.parseColor("#FF1076FF"));
                    hytztv2.setTextColor(Color.parseColor("#FF7D8198"));
                    isybtz = true;
                }
                break;
            case R.id.iv2:
                if (isybtz) {
                    iv2.setBackgroundResource(R.drawable.case_on);
                    iv1.setBackgroundResource(R.drawable.case_off);
                    hytztv2.setTextColor(Color.parseColor("#FF1076FF"));
                    ybtztv1.setTextColor(Color.parseColor("#FF7D8198"));
                    isybtz = false;
                } else {
                    return;
                }
                break;
            case R.id.jsdx_ll:
                if (isybtz) {
                    Intent a = new Intent();
                    a.setClass(FbtzActivity.this, Jsdx1Activity.class);
                    a.putExtra("selectlist", (Serializable) jsdxListBeans);
                    startActivityForResult(a, 1);
                } else {
                    Intent b = new Intent();
                    b.setClass(FbtzActivity.this, Jsdx2Activity.class);
                    b.putExtra("selectlist", (Serializable) jsdxListBeans2);
                    startActivityForResult(b, 2);

                }
                break;
            case R.id.add_ll:
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("*/*");//无类型限制
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, 100);
                break;
            case R.id.del_ll:
                addLl.setVisibility(View.VISIBLE);
                delLl.setVisibility(View.GONE);
                filepath = "";
                fileName.setText("");
                break;
            case R.id.agree_tv:
                progressDialog = new ProgressDialog(this);
                progressDialog.setMessage("正在提交");
                progressDialog.show();
                JSONObject jsonObject = new JSONObject();
                if (TextUtils.isEmpty(filepath)){
                    if (btEt.getText().toString().length() == 0) {
                        Toast.makeText(this, "请输入标题", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    jsonObject.put("TITLE", btEt.getText().toString());
                    if (sffk) {
                        jsonObject.put("IFHF", "1");
                        if (TextUtils.isEmpty(fkqxstr)) {
                            Toast.makeText(this, "请选择反馈时限", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        jsonObject.put("GHFSX", fkqxstr);
                    } else {
                        jsonObject.put("IFHF", "0");
                        jsonObject.put("GHFSX", "");
                    }
                    if (TextUtils.isEmpty(ybtzlsitstr)) {
                        Toast.makeText(this, "请选择接收对象", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    jsonObject.put("select_list", ybtzlsitstr);

                    if (!TextUtils.isEmpty(nr_et.getText().toString())) {
                        jsonObject.put("GCONTENT", nr_et.getText().toString());
                    }
                    jsonObject.put("FXNAME", SpUtil.getString(this, SpUtil.USER_RUN_NICKNAME, ""));
                    jsonObject.put("FORGCODE", SpUtil.getString(this, SpUtil.F_orgcode, ""));
                    jsonObject.put("FORGNAME", SpUtil.getString(this, SpUtil.F_orgname, ""));
                    if (isybtz) {
                        jsonObject.put("TZTYPE", "1");
                    } else {
                        jsonObject.put("TZTYPE", "0");
                    }

                    Log.d("FbtzActivity", jsonObject.toString());
                    NetRequsetUtil.getInstance().netRequestPostJson("v1/center/deliver_an_announcement_function",
                            jsonObject.toString()
                            , new NetDownResponse() {
                                @Override
                                public void success(String str) {
                                    if (progressDialog != null){
                                        progressDialog.dismiss();
                                    }
                                    Toast.makeText(FbtzActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                                    FbtzActivity.this.finish();
                                }

                                @Override
                                public void errowithresponse(String str) {
                                    ErrorBeanUtil.getErrorMessage(str);
                                    if (progressDialog != null){
                                        progressDialog.dismiss();
                                    }
                                }

                                @Override
                                public void erro() {
                                    ErrorBeanUtil.getErrorMessage(null);
                                    if (progressDialog != null){
                                        progressDialog.dismiss();
                                    }
                                }

                                @Override
                                public void finish() {

                                }
                            });
                }else {
                    //附件名称
                    File file = new File(filepath);
                    NetRequsetUtil.getInstance().uploadFile("v1/center/do_upload", filepath, "file_name",
                            file.getName(), new NetUpLoadResponse() {
                                @Override
                                public void success(String str) {
                                    UpSuccessBean upSuccessBean = JSON.parseObject(str, UpSuccessBean.class);
                                    String file_url = upSuccessBean.getFile_url();
                                    final JSONObject jsonObject = new JSONObject();
                                    jsonObject.put("FUJIAN", file_url);


                                    if (btEt.getText().toString().length() == 0) {
                                        Toast.makeText(FbtzActivity.this, "请输入标题", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    jsonObject.put("TITLE", btEt.getText().toString());
                                    if (sffk) {
                                        jsonObject.put("IFHF", "1");

                                    } else {
                                        jsonObject.put("IFHF", "0");
                                    }
                                    if (TextUtils.isEmpty(ybtzlsitstr)) {
                                        Toast.makeText(FbtzActivity.this, "请选择接收对象", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    jsonObject.put("select_list", ybtzlsitstr);
                                    if (TextUtils.isEmpty(fkqxstr)) {
                                        Toast.makeText(FbtzActivity.this, "请选择反馈时限", Toast.LENGTH_SHORT).show();
                                        return;
                                    }
                                    jsonObject.put("GHFSX", fkqxstr);
                                    if (!TextUtils.isEmpty(nr_et.getText().toString())) {
                                        jsonObject.put("GCONTENT", nr_et.getText().toString());
                                    }
                                    jsonObject.put("FXNAME", SpUtil.getString(FbtzActivity.this, SpUtil.USER_RUN_NICKNAME, ""));
                                    jsonObject.put("FORGCODE", SpUtil.getString(FbtzActivity.this, SpUtil.F_orgcode, ""));
                                    jsonObject.put("FORGNAME", SpUtil.getString(FbtzActivity.this, SpUtil.F_orgname, ""));
                                    if (isybtz) {
                                        jsonObject.put("TZTYPE", "1");
                                    } else {
                                        jsonObject.put("TZTYPE", "0");
                                    }

                                    Log.d("FbtzActivity", jsonObject.toString());
                                    NetRequsetUtil.getInstance().netRequestPostJson("v1/center/deliver_an_announcement_function",
                                            jsonObject.toString()
                                            , new NetDownResponse() {
                                                @Override
                                                public void success(String str) {
                                                    Toast.makeText(FbtzActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                                                    FbtzActivity.this.finish();
                                                    if (progressDialog != null){
                                                        progressDialog.dismiss();
                                                    }
                                                }

                                                @Override
                                                public void errowithresponse(String str) {
                                                    ErrorBeanUtil.getErrorMessage(str);
                                                    if (progressDialog != null){
                                                        progressDialog.dismiss();
                                                    }
                                                }

                                                @Override
                                                public void erro() {
                                                    ErrorBeanUtil.getErrorMessage(null);
                                                    if (progressDialog != null){
                                                        progressDialog.dismiss();
                                                    }
                                                }

                                                @Override
                                                public void finish() {

                                                }
                                            });

                                }

                                @Override
                                public void erro() {

                                }
                            });

                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    List<JsdxListBean> selectlist = (List<JsdxListBean>) data.getSerializableExtra("selectlist");
                    jsdxListBeans.clear();
                    jsdxListBeans.addAll(selectlist);
                    qxzTv.setText("已选择");

                    ybtzlsit = new ArrayList<>();
                    for (int i = 0; i < jsdxListBeans.size(); i++) {
                        if (jsdxListBeans.get(i).isSelect()) {
                            ybtzlsit.add(new SelectJsonBean(jsdxListBeans.get(i).getOrgcode(), jsdxListBeans.get(i).getOrgname()));
                        }
                    }
                    Gson gson = new Gson();
                    ybtzlsitstr = gson.toJson(ybtzlsit);
                    Log.d("ssss", ybtzlsitstr);
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    List<JsdxListBean> selectlist = (List<JsdxListBean>) data.getSerializableExtra("selectlist");
                    jsdxListBeans2.clear();
                    jsdxListBeans2.addAll(selectlist);
                    qxzTv.setText("已选择");

                    ybtzlsit2 = new ArrayList<>();
                    for (int i = 0; i < jsdxListBeans2.size(); i++) {
                        for (int j = 0; j < jsdxListBeans2.get(i).getList().size(); j++) {
                            if (jsdxListBeans2.get(i).getList().get(j).isSelect()) {
                                ybtzlsit2.add(new SelectJsonBean(jsdxListBeans2.get(i).getList().get(j).getUserid(),
                                        jsdxListBeans2.get(i).getList().get(j).getXname()));
                            }
                        }
                    }
                    Gson gson = new Gson();
                    ybtzlsitstr = gson.toJson(ybtzlsit2);
                    Log.d("ssss", ybtzlsitstr);
                }
                break;
            case 100:
                if (resultCode == RESULT_OK) {
                    Uri data1 = data.getData();
                    if (data1 == null) {
                        return;
                    }
                    String path = getPath(FbtzActivity.this, data1);
                    filepath = path;
                    File file = new File(path);
                    if (file.exists()) {
                        fileName.setText(file.getName());
                    }
                    addLl.setVisibility(View.GONE);
                    delLl.setVisibility(View.VISIBLE);
                }
                break;
        }
    }

    public String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
//                Log.i(TAG,"isExternalStorageDocument***"+uri.toString());
//                Log.i(TAG,"docId***"+docId);
//                以下是打印示例：
//                isExternalStorageDocument***content://com.android.externalstorage.documents/document/primary%3ATset%2FROC2018421103253.wav
//                docId***primary:Test/ROC2018421103253.wav
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
//                Log.i(TAG,"isDownloadsDocument***"+uri.toString());
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
//                Log.i(TAG,"isMediaDocument***"+uri.toString());
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
//            Log.i(TAG,"content***"+uri.toString());
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
//            Log.i(TAG,"file***"+uri.toString());
            return uri.getPath();
        }
        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public String getDataColumn(Context context, Uri uri, String selection,
                                String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {column};

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    public boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    public boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    public boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

}
